package com.yfp.common.core.domain;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;
import java.util.Optional;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "统一响应对象")
public class CommPacket<T> {
    // 状态
    @Schema(description = "状态")
    private String status;
    // 消息
    @Schema(description = "消息")
    private String message;
    // 数据
    @Schema(description = "数据")
    private Optional<T> payload;

    public static <T> CommPacket<T> successPack(){
      return  new CommPacket<>(
                  "成功",
                "Success",
                Optional.empty()
        );
    }

    public static <T> CommPacket<T> successPack(T payload){
        return new CommPacket<>(
                "成功",
                "Success",
                Optional.ofNullable(payload)
        );
    }

    public static <T> CommPacket<T> funModulePack() {
        return  new CommPacket<>(
                "功能模块异常",
                "The system is busy",
                Optional.empty()
        );
    }

    public static CommPacket failPack(String message, String uuid) {
        return  new CommPacket<>(
                "功能模块异常",
                message,
                Optional.ofNullable(uuid)
        );
    }

    /**
     * 尝试获取值
     * 注意:
     * 如果payload是Map才可能获取到值
     * 其他类型的数据获取不到
     * @param key
     * @return
     * @param <F>
     */
    public <F> Optional<F> tryGetPayloadValue(String key,Class<F> clazz) {
        return payload.flatMap(t -> {
            if (t instanceof Map<?, ?>) {
                Map<?, ?> pay = (Map<?, ?>) t;
                Object value = pay.get(key);
                if (clazz.isInstance(value)) {
                    return Optional.ofNullable(clazz.cast(value));
                }
            }
            return Optional.empty();
        });
    }
}
